<template>
    <div class="container">
        <!-- <div>
            <label for="indexInput">输入索引值：</label>
            <input type="number" id="indexInput" v-model="inputIndex">
            <button @click="calculateLinePosition">确定</button>
        </div> -->
        <div class="line" v-if="showLine"  :style="{ left: linePosition + 'px' }"></div>
        <div class="echart" :id="frequencyId" :style="{ width: width, height: height }" ref="chartContainer"></div>
       
    </div>
</template>

<script>
import * as echarts from "echarts";
// import Decimal from 'decimal.js';
import Decimal from 'decimal.js';


export default {
    name: "Frequency",
    data() {
        return {
            number: null,
            expanded_data: [],
            corresponding_data: [],
            xAxisData: [],
            seriesData: [],
            x_coordinates: [],
            interval: 100, // 间隔长度
            frequencyId: this.generateUniqueId() + "frequencyId",
            option: null,
            chartDom: null,
            myChart: null,
            input_data: null,
            showLine: false,
            linePosition: 0,
            inputIndex: null, // 用户输入的索引值

        };
    },
    props: {
        frequencyNum:{//显示线值
            type: String,
            default: '0',
            required: false // 非必填
        },
        inputData: {
            type: Object,
        },
        height: {
            type: String,
            default: '450px',
        },
        width: {
            type: String,
            default: '100%',
        },
        type: {//1-全频段，2下变频
            type: Number,
            default: 2
        }
    },
    watch: {
        frequencyNum:function(val){
            if(!val){
                return
            }
            this.getCalibrationContrary(val)
        },
        inputData: function (val) {
            if (!val) {
                return
            }
            this.input_data = val
            this.expandData();
            this.initEcharts();
        },

    },
    mounted() {
        if (!this.inputData) {
            return
        }
        this.chartDom = document.getElementById(this.$refs.chartContainer.id);
        this.myChart = echarts.init(this.chartDom);
        this.input_data = this.inputData
        this.expandData();
        this.initEcharts();

    },
    created() {


    },
    methods: {
        calculateLinePosition() {//输入值计算
            // 计算linePosition
            this.linePosition = this.myChart.convertToPixel({ seriesIndex: 0 }, [this.inputIndex*1, this.seriesData[this.inputIndex*1]])[0];
            console.log( this.linePosition);
        },
        generateUniqueId() {
            const timestamp = new Date().getTime().toString(16); // 时间戳的16进制表示
            const randomPart = Math.random().toString(16).substring(2); // 随机数的16进制表示，去掉0.
            const uniqueId = timestamp + randomPart;
            return uniqueId;
        },
        expandData() {
            //y坐标数据
            // 将输入字符串转换为数组
            const dataArray = this.input_data.data.split(",").map(Number);
            // 更新扩展后的数据
            this.seriesData = dataArray
            // 计算每个值对应的数据
            this.seriesData = this.interpolateData(this.seriesData, this.input_data.bandwidth)
            //x坐标数据
        },
        setNumber() {
            console.log(this.number);
            this.$emit("setNumber", this.number);
        },

        getCalibration(val, type) {//计算对应的下标值
            const self = this
            return  val * 1 + (self.input_data.central - self.input_data.bandwidth / 2)
            if(type==1){
                
            }else{
                return  new Decimal(val * 1 + (self.input_data.central - self.input_data.bandwidth / 2)).mul(0.001).toNumber()

            }
             
        },
        getCalibrationContrary(val) {//计算对应的下标值 逆计算 根据值计算位置
            if(this.type == 1){//全频谱才会计算
                this.inputIndex =  (val*1000) - (this.input_data.central - this.input_data.bandwidth / 2)
                console.log(this.inputIndex );
                this.calculateLinePosition()
            }
        },
        initEcharts() {
            const self = this;
            // const interval = self.type == 1 ? 199 : 0.5
            const interval = 199
            this.option = {
                grid: {
                    top: "15%",
                    right: "10%",
                    left: "10%",
                    bottom: "15%",
                },
                xAxis: {
                    splitNumber: 5,
                    type: "category",
                    boundaryGap: false,
                    // data: this.xAxisData,
                    // default: 100,
                    axisLabel: {
                        interval: 299, // 刻度显示间隔
                        show: true,
                        formatter: function (value) {
                            return self.getCalibration(value, self.type);
                        },
                    },
                    offset: 0,
                    axisLine: {
                        onZero: false,
                        lineStyle: {
                            color: 'white', // 刻度线颜色
                        },
                    },
                    axisTick: {//刻度线属性
                        // alignWithLabel: false,
                        // show: false,//刻度线显示
                        lineStyle: {
                            type: 'solid',
                            width: 2, // 设置刻度线宽度
                        },
                    },
                    minorTick: {
                        show: true,
                        splitNumber: 5,
                        length: 3,
                    },
                },
                yAxis: {
                    type: 'value',
                    min: -150, // 设置最小值
                    max: 60, // 设置最大值
                    interval: 10, // 设置分隔为5
                    axisLabel: {
                        margin: 30, // 设置刻度标签的宽度
                    },
                },
                series: {
                    data: this.seriesData,
                    type: "line",
                    lineStyle: {
                        color: "transparent", // 设置线条颜色为白色
                        color: "while", // 设置线条颜色为白色
                        opacity: 0.5,
                    },
                    areaStyle: {
                        color: "#857120", // 设置区域颜色为黄色
                        opacity: 0.5,
                        origin: 'start', // 设置区域样式从y轴的0开始
                    },
                    symbol: "none", // 设置折线上的点的图标为无
                    showSymbol: false, // 隐藏折线上的点
                    emphasis: {
                        focus: 'none', // 禁用悬浮效果
                    },
                    itemStyle: {
                        opacity: 0.5,
                    },
                },
            };
            self.myChart.getZr().on('click', function (params) {
                
                const pointInGrid = self.myChart.convertFromPixel({ seriesIndex: 0 }, [params.offsetX, params.offsetY]);
                const xIndex = Math.round(pointInGrid[0]); // 四舍五入获取最接近的索引值
                // const xIndex = 1000; // 四舍五入获取最接近的索引值
                if (xIndex >= 0 && xIndex < self.seriesData.length) {
                    self.number = self.getCalibration(xIndex, self.type);
                    self.setNumber();
                    self.showLine = true;
                    self.linePosition = self.myChart.convertToPixel({ seriesIndex: 0 }, [xIndex, self.seriesData[xIndex]])[0];
                }
            });


            this.option &&  self.myChart.setOption(this.option);
        },
        // 使用线性插值将数据从原始点数扩展到所需点数 当用户输入bandwidth为2的时候就是2000份，需要将1024分为2000份
        // 数据：dataArray 需要分成的份数：needPoints
        interpolateData(dataArray, needPoints) {
            const originalPoints = dataArray.length;
            const expandedData = [];
            for (let i = 0; i < needPoints; i++) {
                const index = (i / (needPoints - 1)) * (originalPoints - 1);
                const lowerIndex = Math.floor(index);
                const upperIndex = Math.ceil(index);
                const t = index - lowerIndex;

                const interpolatedValue =
                    dataArray[lowerIndex] + t * (dataArray[upperIndex] - dataArray[lowerIndex]);

                expandedData.push(Math.round(interpolatedValue));
            }

            return expandedData;
        },
        beforeDestroy() {
        },
    },
};
</script>

<style rel="stylesheet/scss" lang="scss">
/* Your existing styles */

.ruler {
    position: relative;
    width: 300px;
    height: 50px;
    background-color: #f0f0f0;
    margin-top: 50px;
}

.ruler::before,
.ruler::after {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    width: 1px;
    background-color: #333;
}

.ruler::before {
    left: 0;
}

.ruler::after {
    right: 0;
}

.mark {
    position: absolute;
    width: 1px;
    height: 10px;
    background-color: #333;
    top: 50%;
    transform: translateY(-50%);
}

.mark:nth-child(5n) {
    height: 20px;
    /* 长一些的刻度线，比如每5个刻度为一个大刻度 */
}

.container {
    position: relative;
    //   height: 100px;
    //   width: 200px;
    //   background-color: #f0f0f0;
}

.line {
    position: absolute;
    left: 50%;
    top: 15%;
    transform: translateX(-50%);
    width: 2px;
    height: 70%;
    background-color: #FFE355;
    pointer-events: none;
    /* 防止线条遮挡点击事件 */
}
</style>